package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
//    @XxlJob("processTimeoutOrder")
    public void processTimeoutOrder() {
        log.info("处理支付超时订单:{}", new Date());
        //LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15); // 当前时间减15
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15); // 当前时间减15

        //1. 查询出超时的订单
        List<Orders> orders = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, orderTime);

        if (!CollectionUtils.isEmpty(orders)) {
            //2 修改状态
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时,自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理“派送中”状态的订单
     */
//    @XxlJob("processDeliveryOrder")
    public void processDeliveryOrder() {
        log.info("处理“派送中”状态的订单:{}", new Date());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60); // 当前时间减60
        //LocalDateTime Time = LocalDateTime.now().minusMinutes(60); // 当前时间减15

        //1/ 查询出派送中的订单
        List<Orders> orders = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if (!CollectionUtils.isEmpty(orders)) {
            //2 修改状态
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
